package band

import (
	"github.com/pkg/errors"

	"github.com/brocaar/lorawan"
	loraband "github.com/brocaar/lorawan/band"
	"network/v3/internal/config"
)

var band loraband.Band

// Setup sets up the band with the given configuration.
func Setup(c config.Config) error {
	dwellTime := lorawan.DwellTimeNoLimit
	networkServerCfg := c.NetworkServer
	if networkServerCfg.Band.DownlinkDwellTime400ms {
		dwellTime = lorawan.DwellTime400ms
	}
	baseBand, err := loraband.GetConfig(networkServerCfg.Band.Name, networkServerCfg.Band.RepeaterCompatible, dwellTime)
	if err != nil {
		return errors.Wrap(err, "get band config error")
	}
	for _, extraChannel := range networkServerCfg.NetworkSettings.ExtraChannels {
		if err := baseBand.AddChannel(extraChannel.Frequency, extraChannel.MinDR, extraChannel.MaxDR); err != nil {
			return errors.Wrap(err, "add channel error")
		}
	}
	band = baseBand
	return nil
}

// Band returns the configured band.
func Band() loraband.Band {
	return band
}
